package com.maomao.maomaochong_i.personalPackage;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by maomao on 2017/6/24.
 */

public class CountDownTimerButton extends android.support.v7.widget.AppCompatButton implements
        View.OnClickListener{
    private Context mContext;
    private OnClickListener mOnClickListener;

    //调度器
    private Timer mTimer;
    private TimerTask mTask;

    //倒计时时长(持续时间)，默认为毫秒 1s = 1000
    private long duration = 60000;

    //过渡值(临时的倒计时时长)
    private long temp_duration;

    //点击前后文本变化
    private String buttonBefore = "获取验证码";
    private String buttonAfter = "秒";

    //构造函数1
    public CountDownTimerButton(Context context) {
        super(context);
        mContext = context;
        //调用下面自定义的 setOnClickListener()
        setOnClickListener(this);
    }

    //构造函数2
    public CountDownTimerButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setOnClickListener(this);
    }

    //异步消息
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg){
            CountDownTimerButton.this.setText(temp_duration / 1000 + buttonAfter);
            temp_duration -= 1000;
            if (temp_duration < 0){
                CountDownTimerButton.this.setEnabled(true);
                CountDownTimerButton.this.setText(buttonBefore);
                //调用计时结束方法
                stopTimer();
            }
        }
    };

    public void setOnClickListener(OnClickListener listener){
        if (listener instanceof CountDownTimerButton){
            //调用系统的监听器,因为本类继承了接口，跳到下面的 onClick()
            super.setOnClickListener(listener);
        }else{
            this.mOnClickListener = listener;
        }
    }

    @Override
    public void onClick(View v) {
        if (mOnClickListener != null){
            mOnClickListener.onClick(v);
        }
        //调用计时开始方法
        startTimer();
    }

    //计时开始
    private void startTimer(){
        temp_duration = duration;
        CountDownTimerButton.this.setEnabled(false);
        mTimer = new Timer();
        mTask = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0x01);
            }
        };
        //调度分配（安排），延迟0秒，时间间隔为1秒
        mTimer.schedule(mTask,0,1000);
    }

    //计时结束
    private void stopTimer(){
        if (mTask != null){
            //撤销
            mTask.cancel();
            mTask = null;
        }
        if (mTimer != null){
            //撤销
            mTimer.cancel();
            mTimer = null;
        }
    }
}